package com.dotstone.chipism.activity;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.dotstone.chipism.R;
import com.dotstone.chipism.util.CancelException;
import com.dotstone.chipism.util.SocketManager;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.BadgeView;
import com.dotstone.chipism.view.BaseAnimatorSet;
import com.dotstone.chipism.view.NormalDialog;
import com.dotstone.chipism.view.OnBtnClickL;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class VersionActivity extends BaseActivity {
    private LinearLayout mBackL;
    private TextView mStatusBar;
    private TextView mTitleTv;
    private TextView version_tv;
    private BadgeView badgeView;
    private int localVersion;
    private int latestVersion;
    private NormalDialog mNormalDialog;
    private BaseAnimatorSet bas_in;
    private BaseAnimatorSet bas_out;
    private ProgressDialog pd;
    private boolean downloading = false;
    protected boolean cancelDownload;
    private AlertDialog dialog_download;
    protected int lastProgress;
    private RelativeLayout mUpdateR;


    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.back_layout:
                finish();
                break;
        }
    }

    @Override
    public void initParms(Bundle parms) {

    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_version;
    }

    @Override
    public void initView(View view) {
        mBackL = $(R.id.back_layout);
        mStatusBar = $(R.id.tv_statusBar_mian);
        mTitleTv = $(R.id.title_tv);
        version_tv = $(R.id.version_tv);
        mUpdateR = $(R.id.update_r);
        mTitleTv.setVisibility(View.VISIBLE);
        mTitleTv.setText("版本信息");
        version_tv.setText("Version: "+getCurrentVersion());
        boolVersion();
        // 判断当前软件版本
        // 获取系统版本
        Log.i("wmy", "latestVersion = "+latestVersion+" localVersion = "+localVersion);
        if (latestVersion <= localVersion) {
            ToastShow.Show(getApplicationContext(), "当前版本已是最新");
            return;
        }
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(getApplicationContext(),
                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                boolean should = checkShould();
                if (should) {
                    askPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
                } else {
                    ActivityCompat.requestPermissions(VersionActivity.this, new String[] {
                                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE },
                            0);
                }
            } else {
                downloadNewVersion(SocketManager.getInstance().downloadUrl);
            }
        } else {
            downloadNewVersion(SocketManager.getInstance().downloadUrl);
        }
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        initData();
    }

    @Override
    public void setListener() {
        mBackL.setOnClickListener(this);
    }

    @Override
    public void doBusiness(Context mContext) {

    }

    public void boolVersion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

            Window window = getWindow();
            window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            // getWindow().addFlags(
            // WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            // 改变titlebar的高度
            int statusbarHeight = BarUtils.getStatusBarHeight(this);
            RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) mStatusBar.getLayoutParams();
            layoutParams1.height = statusbarHeight;
            mStatusBar.setLayoutParams(layoutParams1);
            mStatusBar.setVisibility(View.VISIBLE);
        } else {
            mStatusBar.setVisibility(View.GONE);
        }
    }

    public String getCurrentVersion() {
        String versionName ="";
        try {
            PackageInfo pkg = getPackageManager().getPackageInfo(
                    getPackageName(), 0);
            versionName = pkg.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
    private void initData() {
        latestVersion = SocketManager.getInstance().getV();
        localVersion = SocketManager.getInstance().getAppVersion();
        Log.i("wmy", "latestVersion" + latestVersion + " localVersion = " + localVersion);
        if (latestVersion > localVersion) {
            badgeView = new BadgeView(this, mUpdateR);
            badgeView.setText("New");
            badgeView.setTextColor(Color.WHITE);
            badgeView.show();
        }
    }

    Handler mHandler = new Handler() {
        public void handleMessage(final Message msg) {
            switch (msg.what) {
                case 9:
                    downloading = false;
                    pd.dismiss();
                    ToastShow.Show(VersionActivity.this, "下载完成");
                    // 下载完成后安装
                    String savedFilePath = (String) msg.obj;
                    Log.i("wmy", "下载完毕" + savedFilePath);
                    Intent intent = new Intent();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                        intent.setAction(Intent.ACTION_VIEW);
                        Uri contentUri = FileProvider.getUriForFile(getApplicationContext(),
                                "com.dotstone.chipism.fileprovider", new File(savedFilePath));
                        intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
                    } else {
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(new File(savedFilePath)),
                                "application/vnd.android.package-archive");
                    }
                    startActivity(intent);
                    break;
                case 10:
                    pd.setProgress(msg.arg1);
                    break;
                default:
                    break;
            }
        }
    };

    protected void downloadNewVersion(final String urlString) {
        downloading = true;
        pd = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        pd.setMessage(getString(R.string.downloading));
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(false);// android 高版本对话框点击消失
        pd.show();
        pd.setProgress(0);
        pd.setOnDismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface arg0) {
                cancelDownload = true;
            }
        });

        new Thread() {

            public void run() {
                try {
                    InputStream input = null;
                    HttpURLConnection urlConn = null;
                    URL url = new URL(urlString);
                    urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setRequestProperty("Accept-Encoding", "identity");
                    urlConn.setReadTimeout(10000);
                    urlConn.setConnectTimeout(10000);
                    input = urlConn.getInputStream();
                    int total = urlConn.getContentLength();
                    File file = null;
                    OutputStream output = null;
                    if (!new File(android.os.Environment.getExternalStorageDirectory().getPath() + "/cache").exists()) {
                        new File(android.os.Environment.getExternalStorageDirectory().getPath() + "/cache").mkdirs();
                    }
                    // String savedFilePath =
                    // android.os.Environment.getRootDirectory().getPath()
                    // + "/cache/xintek.apk";
                    String savedFilePath = android.os.Environment.getExternalStorageDirectory().getPath()
                            + "/cache/xintek.apk";
                    file = new File(savedFilePath);
                    output = new FileOutputStream(file);
                    byte[] buffer = new byte[1024];
                    int temp = 0;
                    int read = 0;
                    while ((temp = input.read(buffer)) != -1) {
                        if (cancelDownload) {
                            throw new CancelException();
                        }
                        output.write(buffer, 0, temp);
                        read += temp;
                        float progress = ((float) read) / total;
                        int progress_int = (int) (progress * 100);
                        if (lastProgress != progress_int) {
                            lastProgress = progress_int;
                            Message msg = new Message();
                            msg.what = 10;// downloading
                            msg.arg1 = progress_int;
                            mHandler.sendMessage(msg);
                        } else {
                            // do not send msg
                        }
                    }
                    output.flush();
                    output.close();
                    input.close();
                    Message msg = new Message();
                    msg.what = 9;
                    msg.obj = savedFilePath;
                    mHandler.sendMessage(msg);
                } catch (CancelException e) {
                    Log.e("wmy", "取消下载啦");
                    cancelDownload = false;
                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(5);
                }
            };
        }.start();
    }

    @SuppressLint("NewApi")
    private boolean checkShould() {
        if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            Log.e("wmy", "曾被设置永不提示");
            return true;
        } else {
            Log.e("wmy", "未曾设置永不提示");
            return false;
        }
    }

    private void askPermission(String permission) {
        String request = "";
        // if (permission.equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
        request = "储存权限被禁止，是否前往设置界面开启？";
        // }
        mNormalDialog = new NormalDialog(VersionActivity.this);
        mNormalDialog.content(request).style(NormalDialog.STYLE_TWO)//
                .titleTextSize(18)//
                .showAnim(bas_in)//
                .dismissAnim(bas_out)//
                .show();
        mNormalDialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                mNormalDialog.dismiss();
            }
        }, new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                mNormalDialog.dismiss();
                Intent localIntent = new Intent();
                localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                localIntent.setData(Uri.fromParts("package", VersionActivity.this.getPackageName(), null));
                startActivity(localIntent);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Log.e("wmy", "调用权限" + requestCode + " " + permissions[0] + " " +
        // permissions[1] + " " + grantResults[0] + " "
        // + grantResults[1]);
        if (SocketManager.getInstance().downloadUrl != null && permissions[0].equals(Manifest.permission.READ_EXTERNAL_STORAGE)
                && grantResults[0] == 0) {
            downloadNewVersion(SocketManager.getInstance().downloadUrl);
        } else {
            ToastShow.Show(getApplicationContext(), "权限已被禁止");
        }
    }


}
